<?php
/**
 * 继承了最基本的News服务 然后进行扩展
 * 服务类 不能涉及参数和视图操作
 * @author Administrator
 *
 */
class NewsService {
	public $newsModule;
	public function __construct($cid, $mid) {
		$this->newsModule = new News ( $cid, $mid ); //实例化news
	}
	/**
	 * 批量处理article
	 * */
	public function batchArticle() {
		$cleanIds = NewsModel::instance ()->getRecycleNews ( 1067 );
		foreach ( $cleanIds as $v ) {
			$this->cleanOneArticle ( $v ['id'] );
		}
	}
	/**
	 * 删除一篇文章
	 * Enter description here ...
	 * @param unknown_type $id
	 */
	private function cleanOneArticle($id) {
		$con = $this->newsModule->getCon ( $id );
		//	$con = $this->newsModule->_m->getCon ( $id );
		//	print_r ( $con );
		$match = "#src=\"(.*)\"#iUs";
		preg_match_all ( $match, $con ['content'] ['content'], $rs );
		//删除缩略图图片
		unlink ( ROOT . $con ['content'] ['thumb'] );
		unlink ( ROOT . $con ['content'] ['pic'] );
		//删除内容图片
		foreach ( $rs [1] as $v ) {
			if (! unlink ( getcwd() . $v )) {
				//echo $id, " ok!<br>";
				echo $id, " failed<br>";
			}
		}
		//删除文章内容
		NewsModel::instance ()->deleteNews ( $id );
	}
	/**
	 * 根据新闻分类ids获取数量
	 * @param unknown_type $ids
	 */
	public function getNewsNumByIds($cids) {
		return NewsModel::instance ()->getNewsNum ( null, $cids ); //生成的页面数
	}
	/**
	 * 生成静态页面
	 * @param
	 */
	public function html($cid, $id, &$content, $type, $date = NULL) {
		$path = ROOT . "a" . DIRECTORY_SEPARATOR;
		if ($date == null || $date == "null") {
			$date = "197001";
		}
		$ym = date ( "Ym", $date );
		switch ($type) {
			case "V" :
				$filename = $id . ".html";
				break;
			case "C" :
				$ym = "c";
				$filename = $id . ".html";
				break;
			case "I" :
				$ym = "i";
				$id = $cid;
				$filename = $id . ".html";
				break;
		}
		$save_path .= $path . $ym . DIRECTORY_SEPARATOR;
		if (! file_exists ( $save_path )) {
			mkdir ( $save_path );
		}
		$url = '/a/' . $ym . '/' . $filename;
		$file = $save_path . $filename;
		$handle = fopen ( $file, "w" );
		fwrite ( $handle, $content );
		fclose ( $handle );
		//防止全部更新
		if ($type == "V" && $id > 33480) {
			NewsModel::instance ()->saveNews ( array ('html' => $url ), array ('id' => $id ) );
		}
		return true;
	}
	/**
	 * 新增点击量
	 * Enter description here ...
	 */
	public function addViews($id) {
		$rs = NewsModel::instance ()->getNewsWhere ( array ('id' => $id ) );
		$num = $rs ['views'] + 1;
		NewsModel::instance ()->saveNews ( array ('views' => $num ), array ('id' => $id ) );
		return $num;
	}
	public function setNewsSort($sort, $id) {
		return NewsModel::instance ()->setNewsSort ( $sort, $id );
	}
	/**
	 * 复制  删除 移动新闻
	 * Enter description here ...
	 * @param int $ids
	 * @param int $cid
	 * @param String $type
	 */
	public function edit($ids, $cid, $type) {
		$data = substr ( $ids, 1 );
		// 只复制一个的情况
		if (strpos ( $data, "," )) {
			$data = explode ( ",", $data );
			foreach ( $data as $v ) {
				if ($type == 'del') {
					$this->remove ( $v );
				} else if ($type == 'copy') {
					NewsModel::instance ()->copyNews ( $v, $cid );
				} else if ($type == 'move') {
					NewsModel::instance ()->saveNews ( array ('cid' => $cid ), array ('id' => $v ) );
				}
			}
		} else {
			if ($type == 'del') {
				$this->remove ( $data );
			} else if ($type == 'copy') {
				NewsModel::instance ()->copyNews ( $data, $cid );
			} else if ($type == 'move') {
				NewsModel::instance ()->saveNews ( array ('cid' => $cid ), array ('id' => $data ) );
			}
		}
	}
	/**
	 * 分类id
	 * 已经作废
	 *
	 * @return array
	 */
	public function loadTemp($categoryId, $type = "temp_list") {
		// 先检查是否自身绑定
		$cateInfo = $this->getTemp ( $categoryId, $type );
		// var_dump($cateInfo);
		return $cateInfo;
	
		// $this->template($cateInfo[$type]);
	}
	/**
	 * 递归扫描上级分类
	 *
	 * @param int $categoryId
	 * @param String $type
	 * @return
	 *
	 */
	protected function getTemp($categoryId, $type) {
		$rs = NewsModel::instance ()->getCateogryById ( $categoryId );
		if (empty ( $rs )) {
			//分类b
			echo "Add success,but can't create article,please set $categoryId " . $rs [$type] . "template!";
			exit ();
		}
		if ($rs [$type] == "NULL" || empty ( $rs [$type] ) == true || $rs [$type] == "null") {
			$rs = $this->getTemp ( $rs ['fid'], $type );
		} else {
			return $rs;
		}
		return $rs;
	}
	/**
	 * 获取模型模板和缓存id*/
	public function nlist($cid, $p, $tempType) {
		/* 对首页进行缓存 */
		$cateInfo = $this->getTemp ( $cid, $tempType );
		$tempName = "mysql:" . $cateInfo [$tempType];
		// 如果p不存在则默认为1;
		$cate = NewsModel::instance ()->getCateogryById ( $cid ); // 调用父id
		$cacheid = $p > 1 ? $cid . 'p' . $p : $cid;
		return array ('cate' => $cate, 'tempname' => $tempName, 'cacheid' => $cacheid );
	}
	public function getCate($cid, $group) {
		$rs = NewsModel::instance ()->getCateogryById ( $cid );
		$rs ['groupname'] = $group [$rs ['groupid']];
		return $rs;
	}
	public function bindCateTemp($type, $name, $cid) {
		NewsModel::instance ()->bindCategoryById ( array ($type => trim ( $name ) ), $cid );
		return NewsModel::instance ()->getTemplateByName ( trim ( $name ) );
	}
	public function getCateField($cid) {
		$extend = NewsModel::instance ()->getExtend ( array ('module' => 'news' ) );
		$cateInfo = NewsModel::instance ()->getCateExtendByCid ( $cid );
		$selected = array ();
		foreach ( $cateInfo as $v ) {
			array_push ( $selected, $v ['eid'] );
		}
		foreach ( $extend as $k => $v ) {
			if (in_array ( $v ['eid'], $selected )) {
				$extend [$k] ['checked'] = 'checked';
			}
		}
		return $extend;
	}
	/**
	 * 绑定字段
	 * Enter description here ...
	 * @param unknown_type $cid
	 * @param unknown_type $eidArr
	 */
	public function bindField($cid, $eidArr) {
		NewsModel::instance ()->delCateExtend ( $cid );
		foreach ( $eidArr as $v ) {
			NewsModel::instance ()->addCateExtend ( array ('cid' => $cid, 'eid' => $v ) );
		}
		return true;
	}
	
	/**
	 * 获取模块分类
	 * Enter description here ...
	 * @param unknown_type $selectId  当前选中的
	 * @param unknown_type $where
	 */
	public function getCategory($selectId, $where) {
		
		$tree = new Tree ();
		$tree->icon = array ('', '&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;└─ ' );
		$tree->nbsp = '&nbsp;&nbsp;&nbsp;';
		$result = NewsModel::instance ()->getCategory ();
		
		foreach ( $result as $r ) {
			$r ['id'] = $r ['id'];
			$r ['parentid'] = $r ['fid'];
			$r ['selected'] = $selectId == $r ['id'] ? "selected" : "";
			$array [] = $r;
		}
		$tree->init ( $array );
		$str = "<option value='\$id' \$selected>\$spacer\$name</option>";
		$taxonomys = $tree->get_tree ( 0, $str );
		return "<select name=cid id=cate class=\"input-middle\">" . $taxonomys . "</select>";
	}
	/**
	 * 搜索方法 2种类型 精确搜索 模糊搜索
	 * @param unknown_type $key
	 * @param unknown_type $value
	 */
	public function search($key, $value) {
		$type = $this->filterField ( $key );
		$key = $key == 'id' ? 'a.id' : $key;
		switch ($type) {
			case 1 :
				$rs = $this->getNewsByFuzzy ( $key, $value );
				break;
			case 2 :
				$rs = $this->getNewsByFuzzy ( $key, $value );
				break;
			case 3 :
				$rs = $this->getNewsByExtend ( $key, $value );
				break;
		}
		if (empty ( $rs )) {
			return false;
		}
		//获取id集合 增加扩展字段 搜索图集时会有问题//
		foreach ( $rs as $k => $v ) {
			$nrs = $this->newsModule->getCon ( $v ['id'] );
			$rs [$k] = $nrs ['content'];
		}
		
		return $rs;
	}
	/**
	 * 根据内容的分类 绑定所需模板
	 */
	public function setConTemp($id, $temp) {
		$news = $this->newsModule->getCon ( $id ); //获取内容
		$rs = $news ['content'];
		// 设置绑定模板
		if (empty ( $rs ))
			return false;
		
		// 如果循环模板不存在 则提示错误
		$cateInfo = $this->loadTemp ( $rs ['cid'], 'temp_content' );
		//如果链接自带模板 覆盖上方
		if ($temp != NULL) {
			$cateInfo ['temp_content'] = $temp;
		}
		//如果是专题模板 就调用绑定内容的模板页
		if ($rs ['template'] != '') {
			$tempName = "mysql:" . $rs ['template'];
		} else {
			$tempName = "mysql:" . $cateInfo ['temp_content'];
		}
		return array ('content' => $rs, 'tempname' => $tempName );
	}
	/**
	 * 清空统计结果 增加删除多余的扩展字段
	 */
	public function truncate() {
		// 增加一个数据库整理 以提高性能
		NewsModel::instance ()->clearNumCache ();
		$i = 0;
		$i += NewsModel::instance ()->DeleteExtendDecimal ();
		$i += NewsModel::instance ()->DeleteExtendInt ();
		$i += NewsModel::instance ()->DeleteExtendVarchar ();
		return $i;
	}
	/**
	 * 判断字段是否属于基本字段 还是扩展字段
	 * Enter description here ...
	 * @param unknown_type $filed
	 * @return 1模糊搜索 2精确搜索 3扩展字段搜索
	 */
	private function filterField($filed) {
		$base = new BaseModule ();
		//模糊搜索的字段
		if ($filed == "title") {
			return 1;
		}
		if (in_array ( $filed, $base->getKeys () ) || $filed == 'id') {
			return 2;
		}
		return 3;
	}
	/**
	 * 精确搜索 
	 *
	 * */
	private function getNewsByBase($key, $value) {
		$where = array ($key => $value );
		return ModuleModel::instance ()->getModuleBase ( $where, 20 );
	}
	/**
	 * 模糊搜索
	 * @param unknown_type $key
	 * @param unknown_type $name
	 */
	private function getNewsByFuzzy($key, $value) {
		return NewsModel::instance ()->getOneNewsLikeTitle ( $key, $value );
	}
	/**
	 * 根据扩展字段进行搜索
	 * Enter description here ...
	 */
	private function getNewsByExtend($name, $value) {
		$key = NewsModel::instance ()->getExtend ( array ('key' => $name ) );
		$gids = NewsModel::instance ()->getExtendValue ( array ('eid' => $key [0] ['eid'], 'value' => $value, 'moduleid' => '1' ), 'gid' );
		$ids = '';
		foreach ( $gids as $key => $v ) {
			$ids = $ids . $v ['gid'] . ',';
			if ($key >= 20) {
				break;
			}
		}
		$ids = substr ( $ids, 0, strlen ( $ids ) - 1 );
		return NewsModel::instance ()->getNewsListInIds ( $ids, 20 );
	}
}